import {
    EntityComponentTypes,
    ItemLockMode,
    ItemStack,
    Player,
} from "@minecraft/server";
import { Timer } from "@sapi-game/gameComponent/common/timer/timer";
import { GameComponent } from "@sapi-game/main";
import { PixelPartyMainState } from "../states/mainState";

export class PixelPartyPlayerView extends GameComponent<PixelPartyMainState> {
    override onAttach(): void {
        this.start();
        const timer = this.state.getComponent(Timer);
        this.subscribe(timer.events.tick, (t) =>
            this.showTime(t.remainingTime)
        );
    }

    /**刚开始执行 */
    start() {
        this.runner.run(async (r) => {
            for (let i = 0; i < 4; i++) {
                this.context.players.actionbar("§a等待中...");
                await r.wait(20);
            }
        });
        const timer = this.state.getComponent(Timer);
        timer.events.onTime.subscribe(
            () => {
                this.context.players.title("§e§l游戏开始");
            },
            { time: 10, once: true }
        );
    }

    showTime(time: number) {
        if (time <= 10 && time > 0) {
            let color = time == 1 ? "§c" : time == 2 ? "§e" : "§a";
            this.context.players.actionbar(color + time);
        }
        if (time == 3 || time == 2) {
            this.context.players.playSound("note.bit", {
                pitch: 1.05,
                volume: 0.3,
            });
        } else if (time == 1) {
            this.context.players.playSound("note.bit", {
                pitch: 1.55,
                volume: 0.5,
            });
        }
    }

    /**给玩家方块 */
    showColorBlock(block: string) {
        const item = new ItemStack(block);
        item.lockMode = ItemLockMode.slot;
        this.context.players.forEach((p) => {
            this.setHotBarItem(p.player, item);
        });
    }

    private setHotBarItem(p: Player, item: ItemStack) {
        const container = p.getComponent(
            EntityComponentTypes.Inventory
        )?.container;
        if (!container) return;
        for (let i = 0; i < 9; i++) {
            container.setItem(i, item);
        }
    }
}
